package org.jin.samples.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.jin.samples.dao.IScoreDao;
import org.jin.samples.model.CheckUser;
import org.jin.samples.model.ExamScore;
import org.jin.samples.page.PagerModel;
import org.jin.samples.page.SystemContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ScoreDAOImpl extends BaseHibernateDAO<ExamScore> implements IScoreDao{
	
	@Override
	public List<ExamScore> findAllByScoreId(String userId){
		String hql = "FROM ExamScore WHERE user_id = ?";
		List<ExamScore> list = this.queryForList(hql, new Object[]{userId});
		if(list == null){
			return null;
		}
		return list;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public PagerModel<ExamScore> findAllScoreByPage(String id){
		PagerModel<ExamScore> page = new PagerModel<ExamScore>();
		List<ExamScore> dates = new ArrayList<ExamScore>();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getPagesize();
		List<ExamScore> tempDates = this.getSession().createQuery(" from ExamScore where user_id = "+id).setFirstResult(offset).setMaxResults(pageSize).list();
		for(ExamScore score : tempDates){
			dates.add(score);
		}
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		//获取总记录数
		long totalSize = (long)this.getSession().createQuery("select count(*) from ExamScore where user_id = "+id).uniqueResult();
		page.setTotalSize(totalSize);
		return page;	
	}
	
	@Override
	public ExamScore findScoreByUSId(String userId, Integer subjectId)throws Exception{
		String hql = "from ExamScore where user_id = ? and subject_id = ?";
		ExamScore score = this.queryForObject(hql, new Object[] {userId, subjectId});
		return score;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExamScore> checkUser(CheckUser checkUser) throws Exception {
		String n = "";
		String userId ="";
		String subId = "";
		String timeOne = "1000-01-01";
		String timeTwo = "9999-12-31";
		if(checkUser.getSubjectId() != null){
			subId = (checkUser.getSubjectId()).toString();
		}
		if(checkUser.getUser_id() != null){
			userId =(checkUser.getUser_id()).toString();
		}
		if(checkUser.getUser_name() != ""){
			n = checkUser.getUser_name();
		}
		if(checkUser.getTimeOne() != ""){
			timeOne = checkUser.getTimeOne();
		}
		if(checkUser.getTimeTwo() != ""){
			timeTwo = checkUser.getTimeTwo();
		}
		String hql = " from ExamUser where user.user.name LIKE '%"+n+"%' and user.user.user_id LIKE '%"+userId+"%' and sub_id LIKE '%"
				+subId+"%' and exam_time BETWEEN '"+timeOne+"' and '"+timeTwo+"'";
		
		return this.createQuery(hql).list();
	}
	
	
}
